//
//  ZDShoppCarController.m
//  ZDPension
//
//  Created by 刘甲奇 on 2017/6/16.
//  Copyright © 2017年 maker. All rights reserved.
//

#import "ZDShoppCarController.h"
#import "ZDShopCarBar.h"
#import "ZDShoppCarCell.h"
#import "ZDShoppCarGoodsModel.h"

#import "ZDSureOrderController.h"

static NSString *const ZDShoppCarCellId = @"ZDShoppCarCell";

@interface ZDShoppCarController ()

/**
 <#Description#>
 */
@property(nonatomic,strong)UIButton *editButton;
/**
 工具条
 */
@property(nonatomic,strong)ZDShopCarBar *bottomBar;
/**
 是否为编辑状态
 */
@property (nonatomic,assign)BOOL isEditing;
/**
 是否为全选状态
 */
@property (nonatomic,assign)BOOL allSelecting;
/**
 总价
 */
@property (nonatomic,assign) CGFloat totalPrice;
/**
 商品数量
 */
@property (nonatomic,assign) int goodsNumber;
/**
 要结算的数组
 */
@property(nonatomic, strong) NSMutableArray *buyGoods;

@end

@implementation ZDShoppCarController

- (void)setupUI
{
    [super setupUI];
    self.title = @"购物车";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.editButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    CGFloat bottomBarY = 0.0;
    if (LEScreenHeight == 812)
    {
        bottomBarY = LEScreenHeight -statusBarH -navigationBarH -homeBarH -60;
    }else{
        bottomBarY = LEScreenHeight -statusBarH -navigationBarH -60;
    }
    
    ZDShopCarBar *bottomBar = (ZDShopCarBar *)[UIView getNibView:@"ZDShopCarBar"];
    bottomBar.frame = CGRectMake(0, bottomBarY, LEScreenWidth, 60);
    [self.view addSubview:bottomBar];
    self.bottomBar = bottomBar;
     __weak typeof (self) weakSelf = self;
    [bottomBar shopCarBarOpertion:^(NSInteger opertionTag, BOOL allSelect) {
        if (opertionTag == 1)
        {
            //操作到了全选
            [weakSelf handleAllSelecting:allSelect];
        }else if (opertionTag == 2)
        {
            //操作了购买
            [weakSelf handleBuy];
        }
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDShoppCarCell" bundle:nil] forCellReuseIdentifier:ZDShoppCarCellId];
    [self resetTablewFrame:CGRectMake(0, 0, LEScreenWidth, bottomBarY)];
    [self initHeader];
    [self initFooter];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:PAY_SUCCESS_NOTIFICATION object:nil];
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)loadData
{
    [self requestRefreshData];
}
#pragma mark- 网络请求

/**
 刷新数据做了两件事情
 1.判断是否有数据 --- 是否隐藏 工具条和右侧按钮
 2.根据当前的控制是否编辑状态 --- 重新设置商品的状态
 3.刷新数据回来 --- 设置不是全选状态
 */
- (void)requestRefreshData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    [SVProgressHUD showWithStatus:@"正在加载中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:ShoppCarListUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSString *totalPage = successCode[@"page_total"];
        weakSelf.totalPage = totalPage;
        
        NSArray *tempt = datas[@"cart_list"];
        NSArray *tempModel = [ZDShoppCarGoodsModel mj_objectArrayWithKeyValuesArray:tempt];
        
        if (tempModel.count==0)
        {
            //1.隐藏编辑,和工具条
            [weakSelf hiddenBarAndRightItem:YES];
            [weakSelf addNoDataViewWithTipText:@"购物车是空的"];
            [weakSelf.dataSource removeAllObjects];
        }else
        {
             //1.隐藏编辑,和工具条
            [weakSelf hiddenNoDataView];
            [weakSelf hiddenBarAndRightItem:NO];
            
            if (weakSelf.page == 1)
            {
                [weakSelf.dataSource removeAllObjects];
                [weakSelf.dataSource addObjectsFromArray:tempModel];
                
            }else{
                [weakSelf.dataSource addObjectsFromArray:tempModel];
            }
            
            //2.数据回来后设置一遍当前的状态
            [weakSelf setGoodsEditing:weakSelf.isEditing];
            //2.根据编辑状态是否隐藏工具条
            weakSelf.bottomBar.hidden = weakSelf.editing;
            //3.设置不是全选状态
            [weakSelf handleAllSelecting:NO];
            
        }
        [weakSelf.tableView reloadData];
        
        
    } falure:^(NSError *er) {
        ZDLog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];
}

/**
 删除购物车
 1.移除本地数据,判断本地数据源是否为空.
 2.空的话请求下最新,为的是设置空界面的展示.

 @param model <#model description#>
 */
- (void)requestDeleteShopCar:(ZDShoppCarGoodsModel *)model
{
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:model.cart_id forKey:@"cart_id"];
        
        [SVProgressHUD showWithStatus:@"狠心删除中..."];
        __weak typeof (self) weakSelf = self;
        [API requestPostAppendKey:DeleteShopCarUrl params:dict success:^(NSDictionary *successCode) {
            [SVProgressHUD dismiss];
            ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
            id datas = successCode[@"datas"];
            if ([datas isKindOfClass:[NSDictionary class]])
            {
                NSString *error = datas[@"error"];
                if (error)
                {
                    [SVProgressHUD showErrorWithStatus:error];
                }
            }else if ([datas isKindOfClass:[NSString class]])
            {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [weakSelf.dataSource removeObject:model];
                if (weakSelf.dataSource.count == 0)
                {
                    self.page = 1;
                    [weakSelf requestRefreshData];
                }else{
                    [weakSelf.tableView reloadData];
                }
            }
        } falure:^(NSError *er) {
            ZDLog(@"%s---%d---%@",__func__,__LINE__,er);
            [SVProgressHUD dismiss];
        }];
}
- (void)requestEditShoppCarGoodsNumber:(ZDShoppCarGoodsModel *)model
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:model.cart_id forKey:@"cart_id"];
    [dict setObject:model.goods_num forKey:@"quantity"];
    
    [SVProgressHUD showWithStatus:@"修改数量中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:EditShoppCarGoodsNumberUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSString *error = datas[@"error"];
        if (error)
        {
            [SVProgressHUD showErrorWithStatus:error];
        }else{
            
            model.goods_num = [NSString stringWithFormat:@"%@",datas[@"quantity"]];
            model.goods_price = [NSString stringWithFormat:@"%@",datas[@"goods_price"]];
            model.goods_sum = [NSString stringWithFormat:@"%@",datas[@"total_price"]];
            
            //替换数据,刷新界面
            [weakSelf.dataSource replaceObjectAtIndex:model.indexPath.row withObject:model];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[model.indexPath] withRowAnimation:UITableViewRowAnimationFade];
            //如果是选择状态,更新 bar
            if (model.isSelecting)
            {
                [weakSelf caculatePriceGoodsNumberAndSetBar];
            }
        }

    } falure:^(NSError *er) {
        ZDLog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];

}
#pragma mark- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDShoppCarCell *cell = [tableView dequeueReusableCellWithIdentifier:ZDShoppCarCellId forIndexPath:indexPath];
    ZDShoppCarGoodsModel *model = self.dataSource[indexPath.row];
    model.indexPath = indexPath;
    cell.model = model;
     __weak typeof (self) weakSelf = self;
    [cell shopCarOpertion:^(NSInteger opertionTag, ZDShoppCarGoodsModel *model){
        if (opertionTag == 1)
        {
            //选择
            [weakSelf handleSelecting:model];
        }else if (opertionTag == 2)
        {
            //加减
            [weakSelf handleAddAndMinus:model];
        }else if (opertionTag == 3)
        {
            //删除
            [weakSelf handleDelete:model];
        }
    }];
    return cell;
}

#pragma mark- 点击事件

/**
 点击编辑

 @param sender <#sender description#>
 */
- (void)editClick:(UIButton *)sender
{
    NSString *title = _isEditing ? @"编辑":@"完成";
    [self.editButton setTitle:title forState:0];
    _isEditing = !_isEditing;
    
    //设置数据源中商品的状态
    [self setGoodsEditing:_isEditing];
    
    //是否为隐藏工具条
    self.bottomBar.hidden = self.isEditing;
}

/**
 处理删除操作

 @param model <#model description#>
 */
- (void)handleDelete:(ZDShoppCarGoodsModel *)model
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"要狠心删除吗?" preferredStyle:UIAlertControllerStyleAlert];
     __weak typeof (self) weakSelf = self;
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //发送删除请求
        ZDLog(@"%s---%d---删除操作哈",__func__,__LINE__);
        [weakSelf requestDeleteShopCar:model];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"算了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:sureAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

/**
 全选操作
 
 @param allSelecting <#allSelecting description#>
 */
- (void)handleAllSelecting:(BOOL)allSelecting
{
    _allSelecting = allSelecting;
    
    //设置选择状态
    for (ZDShoppCarGoodsModel *model in self.dataSource)
    {
        model.isSelecting = allSelecting;
    }
    
    //计算价格设置工具条
    [self caculatePriceGoodsNumberAndSetBar];
    
    //设置工具条的全选按钮
    [self.bottomBar setAllSelecting:allSelecting];
    
    //设置数据
    [self.tableView reloadData];
}

/**
 去购买
 */
- (void)handleBuy
{
     ZDLog(@"%s---%d---总价: %.2f---数量: %d",__func__,__LINE__,self.totalPrice,self.goodsNumber);
    if (self.goodsNumber == 0) {
        [SVProgressHUD showInfoWithStatus:@"选择要结算的商品"];
    }else{
        ZDSureOrderController *sureOrder = [[ZDSureOrderController alloc] init];
        sureOrder.buyGoods = self.buyGoods;
        sureOrder.buyTpye = ShopCarBuy;
        sureOrder.totalPrice = [NSString stringWithFormat:@"总计: %.2f",self.totalPrice];
        [self.navigationController pushViewController:sureOrder animated:YES];
    }

}

/**
 处理选中的模型
 1.计算价格设置 bar
 2.遍历是否为全选
 
 @param selectedModel <#selectedModel description#>
 */
- (void)handleSelecting:(ZDShoppCarGoodsModel *)selectedModel
{
    [self caculatePriceGoodsNumberAndSetBar];

    self.allSelecting = YES;
    for (ZDShoppCarGoodsModel *model in self.dataSource) {
        if (model.isSelecting == NO)
        {
            self.allSelecting = NO;
        }
    }
    [self.bottomBar setAllSelecting:self.allSelecting];
}
/**
 处理加减数量

 @param model
 */
- (void)handleAddAndMinus:(ZDShoppCarGoodsModel *)model
{
    [self requestEditShoppCarGoodsNumber:model];
}
- (void)refreshData:(NSNotification *)notification
{
    [self requestRefreshData];
}
#pragma mark- privateMethod

/**
 是否隐藏工具条和导航右按钮

 @param hidden <#hidden description#>
 */
- (void)hiddenBarAndRightItem:(BOOL)hidden
{
    self.editButton.hidden = hidden;
    self.bottomBar.hidden = hidden;
}
/**
 设置商品是够为编辑状态

 @param editing <#editing description#>
 */
- (void)setGoodsEditing:(BOOL)editing
{
    for (ZDShoppCarGoodsModel *model in self.dataSource)
    {
        model.isEditing = editing;
    }
    [self.tableView reloadData];
}
- (void)caculatePriceGoodsNumberAndSetBar
{
    //遍历数据源,计算价格,商品数目.
    float totalPrice = 0.0;
    int goodsNumber = 0;

    self.buyGoods = [NSMutableArray array];
    
    for (ZDShoppCarGoodsModel *model in self.dataSource)
    {
        if (model.isSelecting)
        {
            [self.buyGoods addObject:model];
            
            totalPrice += [model.goods_sum floatValue];
            goodsNumber += [model.goods_num intValue];
        }

    }
    self.totalPrice = totalPrice;
    self.goodsNumber = goodsNumber;
    
    //设置工具条的价格数量
    [self.bottomBar setTotalPrice:[NSString stringWithFormat:@"%.2f",totalPrice] goodsNumber:[NSString stringWithFormat:@"%d",goodsNumber]];
}

#pragma mark- getter
- (UIButton *)editButton
{
    if (_editButton == nil) {
        _editButton = [UIButton buttonWithType:0];
        [_editButton setTitle:@"编辑" forState:0];
        _editButton.bounds = CGRectMake(0, 0, 45, 30);
        [_editButton addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editButton;
}
@end
